<?php
/**
 * Copyright (C), 2020-2021, Shall Buy Life info. Co., Ltd.
 * FileName: VerifyStaffPermissionsService.php
 * Description: 验证后台员工权限 单例模式
 *
 * @author lwl
 * @Create Date    2021/6/9 20:55
 * @Update Date    2021/6/16 20:55 By lwl
 * @version v1.0
 */

namespace Example\Services\Staff;

use Example\Constants\CodeMessageConstant;
use Example\Models\AccessRight;

class VerifyPermissionsService
{
    private static $instance = null;

    /**
     * FunctionName：getInstance
     * Description：获取实例
     * Author：lwl
     * @return VerifyPermissionsService|null
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Verify constructor.
     */
    private function __construct()
    {

    }

    /**
     * FunctionName：__clone
     * Description：私有clone
     * Author：lwl
     */
    private function __clone()
    {

    }

    /**
     * FunctionName：__wakeup
     * Description：私有wakeup
     * Author：lwl
     */
    private function __wakeup()
    {

    }

    /**
     * FunctionName：verify
     * Description：验证后台员工权限
     * Author：lwl
     * @param string $publicKey
     * @param string $time
     * @param string $sign
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \ShallBuy\LaravelBase\Common\Exception\Exceptions\BusinessException
     */
    public function verify(string $publicKey, string $time, string $sign)
    {
        $result = AccessRight::query()->where(['public_key' => $publicKey])->first();
        if (!$result) {
            fail(CodeMessageConstant::ERROR_NO_ACCESS);
        }

        if ($sign != getSign($result['private_key'], $time)) {
            fail(CodeMessageConstant::ERROR_SIGNATURE_VERIFY_FAILED);
        }

        if ($result['status'] == CodeMessageConstant::CLOSE) {
            fail(CodeMessageConstant::ERROR_NO_ACCESS);
        }
        $this->cacheStaffBusinessId($result);
        unset($result['private_key']);
        return $result;
    }

    /**
     * FunctionName：cacheStaffBusinessId
     * Description：缓存员工业务id
     * Author：lwl
     * @param $result
     */
    protected function cacheStaffBusinessId($result)
    {
        $cacheConfig = config('common.cache.staff');
        redis()::setex($cacheConfig['permissions'] . $result['public_key'], $cacheConfig['permissions_ttl'], $result['business_id']);
    }
}
